package com.example.web.system;

import cn.dev33.satoken.annotation.SaIgnore;
import com.example.common.constant.Constants;
import com.example.common.helper.LoginHelper;
import com.example.common.vo.R;
import com.example.entity.system.SysMenu;
import com.example.entity.system.req.LoginBody;
import com.example.entity.system.vo.RouterVo;
import com.example.entity.system.vo.VueRouterVo;
import com.example.service.system.ISysMenuService;
import com.example.service.system.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统登录其他
 *
 * @author Administrator
 * @date 2022/10/24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("user")
public class SystemLoginRest {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/signIn")
    public R<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUserName(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }


    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/signOut")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters1")
    public R<List<RouterVo>> getRouters1() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @SaIgnore
    public R<List<VueRouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildVueMenus(menus));
    }
}
